﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;
using FreesenseSubAIS.ImageProcess;
using System.Xml.Serialization;

namespace FreesenseSubAIS.Core
{
   public class Utiles
    {

        #region  获取当前日期
        /// <summary>
        /// 获取当前日期
        /// </summary>
        /// <returns></returns>
        public  string GetCurrentDay()
        {
            var n = DateTime.Now;
            var d = n.Year.ToString("d4") + n.Month.ToString("d2") + n.Day.ToString("d2");
            return d;
        }
        #endregion  获取当前日期

        #region 保存日志
        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="data"></param>
        public static  void SaveDebugLog(StringBuilder  data,string cameraid)
        {
            data.Replace("##", "\r\n");
            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", cameraid,DateTime .Now .ToString ("yyyyMMdd"));
            if (!File.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (StreamWriter sw = new StreamWriter(path+"\\LogInfo.txt", true))
            {
                sw.WriteLine(data);
                sw.Close();
            }
        }
        public static void SaveDebugLog(string data, string cameraid)
        {
            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", cameraid, DateTime.Now.ToString("yyyyMMdd"));
            if (!File.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (StreamWriter sw = new StreamWriter(path + "\\LogCorrect.txt", true))
            {
                sw.WriteLine(data);
                sw.Close();
            }
        }
        #endregion 保存日志

        /// <summary>
        /// 计算时间差，单位毫秒
        /// </summary>
        /// <param name="dt1">开始时间</param>
        /// <param name="dt2">结束时间</param>
        /// <returns>时间差</returns>
        public  int TransTime(DateTime dt)
        {
            return Toint(DateTime.Now) - Toint(dt);
        }

        public static void SaveLoadingLog(string data, string filedate)
        {
            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", "启动日志");
            if (!File.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (StreamWriter sw = new StreamWriter(path + string.Format("\\{0}.txt", filedate), true))
            {
                sw.WriteLine(data);
                sw.Close();
            }
        }

        private  int Toint(DateTime dt)
        {
            return (dt.Minute * 60 * 1000 + dt.Second * 1000 + dt.Millisecond);
        }
        private  void CreateRecordsXmlDatabase(string fullsavepath)
        {
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("RECORDS"));
            xdoc.Save(fullsavepath);
        }
        public  int SaveRecord(ref List<Tuple <string,int>> Rec,string cameraname)
        {
            string batchDate = DateTime.Now.ToString("yyyyMMdd").Replace("/", "");
            string batchTime = DateTime.Now.ToString("yyyyMMddHHmmss").Replace("/", "").Replace(":", "");
            string path0 = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", Device.Parameter.DefaultProductId);
            if (!File.Exists(path0))
            {
                Directory.CreateDirectory(path0);
            }
            string path = Path.Combine(path0, batchDate + cameraname + "_Record.xml");//xml
            if (!File.Exists(path))
            {
                CreateRecordsXmlDatabase(path);
            }
            try
            {
                XDocument RecordsDB = XDocument.Load(path);
                var xmlTodaysLog = (from data in RecordsDB.Element("RECORDS").Elements("BATCH") where data.Attribute("DATE").Value == batchDate select data);
                List<XAttribute> XAt = new List<XAttribute>();
                foreach (var ls in Rec)
                {
                    //XAt.Add(new XAttribute(ls.ItemName, ls.DurTime));
                    XAt.Add(new XAttribute(ls.Item1 , ls.Item2 ));
                }
                if (xmlTodaysLog.Count() == 0)
                {

                    RecordsDB.Element("RECORDS").Add(new XElement("BATCH"
                       , new XAttribute("DATE", batchDate)
                       , new XElement("PROJECT"
                           , XAt
                        )));

                }
                else
                {
                    xmlTodaysLog.First().Add(new XElement("PROJECT" , XAt));
                }
                RecordsDB.Save(path, SaveOptions.OmitDuplicateNamespaces);
                //FSCbmsAis.Core.Utiles.SaveDebugLog("记录保存用时：" + FSCbmsAis.Core.Utiles.TransTime(MainForm.Start0));
                XAt.Clear();
                Rec.Clear();
                return xmlTodaysLog.Count();
            }
            catch (Exception ex)
            {
                batchDate = ex.TargetSite + ex.Message;
                //ImageManage.Instance.CmdListStr.Add("xxxxxxxxx卡点计时保存失败：" + batchDate);
                return -1;
            }
        }
        public static int LoadIDNum()
        {
            string recorderxml = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", "LogID.xml");
            if (!File.Exists(recorderxml))
                return 0;
            XDocument RecordsDB = XDocument.Load(recorderxml);
            string batchDate = DateTime.Now.ToString("yyyyMMdd").Replace("/", "");
            var xmlTodaysLog = (from data in RecordsDB.Element("RECORDS").Elements("BATCH").Elements("PROJECT")
                                where data.Parent.Attribute("DATE").Value == batchDate
                                select data);// == batchDate
            return xmlTodaysLog.Count();
        }
        /// <summary>
        /// 查询指定日期数量
        /// </summary>
        /// <param name="datestr">日期</param>
        /// <returns></returns>
        public static int LoadIDNum(string datestr)
        {
            string recorderxml = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", "LogID.xml");
            if (!File.Exists(recorderxml))
                return 0;
            XDocument RecordsDB = XDocument.Load(recorderxml);
            string batchDate = DateTime.Now.ToString("yyyyMMdd").Replace("/", "");
            var xmlTodaysLog = (from data in RecordsDB.Element("RECORDS").Elements("BATCH").Elements("PROJECT")
                                where data.Parent.Attribute("DATE").Value == datestr
                                select data);// == batchDate
            return xmlTodaysLog.Count();
        }

        #region XML 序列化与反序列化

        /// <summary>
        /// 序列化保存到XML文件中
        /// </summary>
        /// <param name="fileName">文件完整路径</param>
        /// <param name="obj">需要保存的对象</param>
        /// <returns></returns>
        public static ExecuteResult SaveToXML(string fileName, object obj)
        {
            ExecuteResult result = new ExecuteResult();
            try
            {
                if (!File.Exists(fileName))
                {
                    FileStream fs = File.Create(fileName);
                    fs.Close();
                }
                using (FileStream fs = new FileStream(fileName, FileMode.Truncate, FileAccess.ReadWrite))
                {
                    XmlSerializer xml = new XmlSerializer(obj.GetType());
                    xml.Serialize(fs, obj);
                }
                result.Status = true;
                result.Message = "保存成功";
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = ex.Message;
                result.Exceptions = ex;
            }
            return result;
        }

        /// <summary>
        /// 反序列化从xml文件中读取
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Object LoadFromXML(string fileName, Type type)
        {
            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region nodeXML
        /// <summary>
        /// XML序列化某一类型到指定的文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        public static void SerializeToXml<T>(string filePath, T obj)
        {
            try
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    xs.Serialize(writer, obj);
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 从某一XML文件反序列化到某一类型
        /// </summary>
        /// <param name="filePath">待反序列化的XML文件名称</param>
        /// <param name="type">反序列化出的</param>
        /// <returns></returns>
        public static T DeserializeFromXml<T>(string filePath)
        {
            try
            {
                if (!System.IO.File.Exists(filePath))
                    throw new ArgumentNullException(filePath + " not Exists");

                using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
                {
                    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        #endregion
    }
}
